<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref } from 'vue'
import useSchema from './hooks/useSchema'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { FormRules, ElMessage } from 'element-plus'
import { SchemaConfig } from '@/api/product/types'
import { getFieldEnumApi, getInfoApi } from '@/api/product'
import { Dialog } from '@/components/Dialog'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getCategorySelectTree } from '@/api/category'
import { getBrandListApi } from '@/api/brand'
import { useRoute } from 'vue-router'

defineOptions({
  name: 'ProductSave'
})

const { t } = useI18n()

const { query, ...route } = useRoute()
const props = withDefaults(
  defineProps<{
    index: number
  }>(),
  {
    index: 0
  }
)

const categoryList = ref([])
const brandList = ref([])
const fieldEnum = ref([])
const modelList = ref([])

const getCategoryList = async () => {
  const res = await getCategorySelectTree({ name: 'Shanghai' })
  if (res) {
    categoryList.value = res.data.list
  }
}

const getBrandList = async () => {
  const res = await getBrandListApi({})
  if (res) {
    brandList.value = res.data.list
  }
}

const getFieldEnum = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  if (res) {
    fieldEnum.value = res.data
    modelList.value = res.data.model
  }
}

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const fetchData = async () => {
  await getCategoryList()
  await getBrandList()
  await getFieldEnum()

  // 在获取完所有数据后， 继续执行您希望在获取完数据后执行的代码
  const schemaConfig: SchemaConfig = {
    productPreViewIdStore,
    setValues,
    categoryList,
    brandList,
    fieldEnum,
    modelList
  }
  const { crudSchemas } = useSchema(schemaConfig)
  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)
  allSchemas.value = {
    formSchema: newSchemas.formSchema || []
  }
}

const productPreViewId = 'productPreView'
const productPreViewIdStore = preViewDialogStore(productPreViewId)

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const rules: FormRules = reactive({})

const getTableDet = async () => {
  if (!query.id) {
    return
  }
  const res = await getInfoApi(query.id as string)
  if (props.index === 1) {
    // 新增数据
    delete (res.data as any).id
  }
  // 处理基础类型转换
  res.data.status = Number(res.data.status)
  res.data.is_advance = Number(res.data.is_advance)
  res.data.billing_weight = Number(res.data.billing_weight)
  res.data.weight = Number(res.data.weight)
  ;(res.data as any).gross_weight = Number(res.data.gross_weight)

  // 安全处理 package_size（核心修复）
  const sizeParts = res.data.package_size?.split('*') || [] // 空值返回空数组
  res.data.size = sizeParts // 保留原始拆分结果（可选）

  // 确保长宽高有默认值，且转换为数字类型
  ;(res.data as any).package_length = sizeParts[0] ? Number(sizeParts[0]) || 0 : 0
  ;(res.data as any).package_width = sizeParts[1] ? Number(sizeParts[1]) || 0 : 0
  ;(res.data as any).package_height = sizeParts[2] ? Number(sizeParts[2]) || 0 : 0

  // 处理 release_date 格式转换（核心修复）
  if (res.data.release_date) {
    const releaseDateStr = String(res.data.release_date)
    // 将 202512 格式转换为 2025-12 格式
    if (releaseDateStr.length === 6 && /^\d{6}$/.test(releaseDateStr)) {
      const year = releaseDateStr.substring(0, 4)
      const month = releaseDateStr.substring(4, 6)
      res.data.release_date = `${year}-${month}`
    }
  }

  if (res) await setValues(res.data)
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    for (const key in formData) {
      if (formData.hasOwnProperty(key) && key.includes('undefined')) {
        delete formData[key]
      }
    }
    if (!formData.main_photo || !formData.main_photo.length) {
      ElMessage.error('商品主图为必填')
      return
    }
    formData.package_size =
      formData.package_length + '*' + formData.package_width + '*' + formData.package_height

    // 处理 release_date 格式转换（提交时转换回 YYYYMM 格式）
    if (formData.release_date) {
      const releaseDateStr = String(formData.release_date)
      // 将 2025-12 格式转换为 202512 格式
      if (releaseDateStr.includes('-') && /^\d{4}-\d{2}$/.test(releaseDateStr)) {
        formData.release_date = releaseDateStr.replace('-', '')
      }
    }

    return formData
  }
}

const reset = () => {
  setValues(
    {
      main_photo_urls: [],
      photo_urls: []
    },
    true
  )
  nextTick(async () => {
    const elForm = await getElFormExpose()
    elForm?.resetFields()
  })
}

const initForm = async () => {
  await fetchData()
  await getTableDet()
}

onMounted(() => {
  if (route.meta.noCache) {
    initForm()
  }
})

onActivated(() => {
  initForm()
})

defineExpose({
  submit,
  reset
})
</script>

<template>
  <Dialog
    v-model="productPreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="productPreViewIdStore.src" alt="Preview Image" />
  </Dialog>

  <Form
    v-if="allSchemas.formSchema && allSchemas.formSchema.length > 0"
    :rules="rules"
    @register="formRegister"
    :schema="allSchemas.formSchema"
  />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
